package vn.edu.uit.chemistry;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Map;

import vn.edu.uit.chemistry.utilities.TCPClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class GiaiTri extends Activity{
	
	Button btnBatDau;
	int kichHoat = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_giai_tri);
		
		SharedPreferences prefs = getSharedPreferences("GiaiTri", 0);
		kichHoat = prefs.getInt("kichHoat", 0);
		
		btnBatDau = (Button) findViewById(R.id.btnBatDau);
		btnBatDau.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				if (kichHoat == 0) {
					new KichHoatGameAsyncTask(getApplicationContext()).execute();
					SharedPreferences prefs = getSharedPreferences("GiaiTri", 0);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putInt("kichHoat", 1);
					editor.commit();
					//kichHoat = 1;
				}
				
				Intent i = new Intent(getApplicationContext(), CapNhatGameShow.class);
				startActivity(i);
			}
		});
	}
	
	
	final class KichHoatGameAsyncTask extends AsyncTask<Void, Void, Void> {

		Context ctx;
		
		public KichHoatGameAsyncTask(Context _ctx) {
			this.ctx = _ctx;
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences prefs = getSharedPreferences("DSNhom", 0);
			Map<String, ?> keys = prefs.getAll();
			for (Map.Entry<String, ?> entry : keys.entrySet()) {
				entry.getKey();
				String[] values = entry.getValue().toString().split("#");
				
				try {
					TCPClient client = new TCPClient(ctx, entry.getKey(), Integer.parseInt("54321"));
					client.kichHoatGame();
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}
}
